const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
var app = getApp();
Page({
     data: {
          //第一次调用微信登录接口
          firstgo: true,
          //公告通知栏
          text: '商城即将上线，敬请期待！',
          marqueePace: 1, //滚动速度
          marqueeDistance: 0, //初始滚动距离
          marqueeDistance2: 0,
          marquee2copy_status: false,
          marquee2_margin: 60,
          size: 14,
          orientation: 'left', //滚动方向
          intervaltop: 40, // 时间间隔

          //swiper图片轮播
          imgUrls: [
               '/images/home/top-1.jpg',
               '/images/home/top-2.jpg',
               '/images/home/top-3.jpg',
          ],
          indicatorDots: false,
          autoplay: false,
          intervalswiper: 3000,
          duration: 800,

          ShopGoods: [], //套餐服务
          hotGoods: [], //热销商品
          hotnum: 6, //热销商品个数
          newGoods: [], //新品上架
          newnum: 6, //新商品个数

          myAgentList: {
               hasMore: true,
               list: [],
               listSize: 0
          },
          startNum: 1, //页数
     },

     todevicegoods: function () {
          wx.navigateTo({
               url: '/pages/home/shop/shop',
          })
     },

     tohotgoods: function () {
          wx.navigateTo({
               url: '/pages/home/hotgoods/hotgoods',
          })
     },
     tonewgood: function () {
          wx.navigateTo({
               url: '/pages/home/newgoods/newgoods',
          })
     },

     // 
     // 轮播跳转事件 type  1 商品   2 页面
     gotoActive: function (event) {
          if (event.currentTarget.dataset.type == '1') {
               wx.navigateTo({
                    url: '/pages/goods/goods?id=' + event.currentTarget.dataset.url
               })
          } else {
               wx.navigateTo({
                    url: '/pages/home/active/active?url=' + event.currentTarget.dataset.url
               })
          }
     },

     getIndexData: function () {
          let that = this;
          var hotnum = that.data.hotnum;
          var newnum = that.data.newnum;

          that.listPage({
               isOnSale: 1,
               isHot: 1,
               orderById: 4
          }, hotnum, {
                    isOnSale: 1,
                    isNew: 1,
                    orderById: 2
               }, newnum)
     },

     //分页查热门、新品列表
     listPage: function (datahot = {}, hotnum, datanew = {}, newnum) {
          var that = this;
          var pageNum = that.data.startNum
          var url = 'current=' + pageNum + '&size=';

          //设置顶部公告
          util.request(api.getMyNews, {}, "GET").then(function (res) {
               wx.hideLoading();
               if (res) {
                    var text = '';
                    res.forEach(element => {
                         text += element.content;
                    })
                    that.setData({
                         text: text
                    });
               } else {
                    console.log("请检查网络!")
               }
          }).catch(function (res) {
               console.log("请求失败！")
          })
          //获取首页轮播图
          util.request(api.getMyBanner + '1', {}, "GET").then(function (res) {
               wx.hideLoading();
               if (res) {
                    that.setData({
                         imgUrls: res
                    });
               } else {
                    console.log("请检查网络!")
               }
          }).catch(function (res) {
               console.log("请求失败！")
          })

          //获取app名称
          util.request(api.getAPPName, {}, "GET").then(function (res) {
               wx.hideLoading();
               if (res) {
                    wx.setNavigationBarTitle({
                         title: res.name
                    })
               } else {
                    console.log("请检查网络!")
               }
          }).catch(function (res) {
               console.log("请求失败！")
          })

          //获取首页套餐服务列表
          // util.request(api.ShopGoodList + url, {
          //      "status": "1"
          // }, "POST").then(function (res) {
          //      wx.hideLoading();
          //      if (res) {
          //           var newData = [];
          //           newData = res.records;
          //           that.setData({
          //                ShopGoods: newData,
          //           });
          //      } else {
          //           console.log("服务套餐列表获取不成功！")
          //      }
          // }).catch(function (res) {
          //      console.log("请求失败！")
          // })

          //获取首页热门商品列表
          util.request(api.HomeUrl + url + hotnum, datahot, "POST").then(function (res) {
               wx.hideLoading();
               if (res) {
                    var newData = [];
                    newData = res.records;
                    that.setData({
                         hotGoods: newData,
                    });
               } else {
                    console.log("热门商品列表获取不成功！")
               }
          }).catch(function (res) {
               console.log("请求失败！")
          })
          //获取首页新品商品列表
          util.request(api.HomeUrl + url + newnum, datanew, "POST").then(function (res) {
               wx.hideLoading();
               if (res) {
                    var newData = [];
                    newData = res.records;
                    that.setData({
                         newGoods: newData,
                    });
               } else {
                    console.log("新进商品列表获取不成功！")
               }
          }).catch(function (res) {
               console.log("请求失败！")
          })

     },

     //分享
     onShareAppMessage: function () {
          wx.showShareMenu({
               withShareTicket: true
          })
          let userinfo = wx.getStorageSync('userInfo');
          console.log(userinfo.id)
          return {
               title: '商城小程序',
               path: 'pages/home/home?id=' + userinfo.id,
               success: function (res) {
                    console.log(res);
                    if (res.errMsg == 'shareAppMessage:ok') {
                         if (res.shareTickets == undefined) { //判断分享结果是否有群信息
                              //分享到好友操作...
                         } else {
                              //分享到群操作... 
                              var shareTicket = res.shareTickets[0];
                              wx.getShareInfo({
                                   shareTicket: shareTicket,
                                   success: function (e) {
                                        //当前群相关信息 
                                        var encryptedData = e.encryptedData;
                                        var iv = e.iv;
                                   }
                              })
                         }
                    }
               }
          }
     },
     // 绑定用户
     requestBindUser: function (userid) {
          //
          var stroRefCode = wx.getStorageSync('refCode');
          console.log(stroRefCode)
          if (stroRefCode.id) {
               return;
          }
          //介绍人code
          wx.setStorageSync('refCode', userid);
     },

     onLoad: function (e) {
          //点击分享的面板进入的小程序 
          if (e && e.id) {
               console.log("介绍人id:" + e.id);
               this.requestBindUser(e);
          } else {
               console.log("无介绍人");
               var e = {
                    id: 0
               }
               this.requestBindUser(e);
          }
          this.getIndexData();
     },
     onReady: function () {
          var that = this;
          wx.getLocation({
               type: '',
               altitude: true,
               success: function (res) {
                    // var latitude = res.latitude + 0.001276
                    // var longitude = res.longitude + 0.006256
                    wx.setStorageSync('location', res);
                    console.log("-----" + wx.getStorageSync('location'))
               },
               fail: function (res) { },
               complete: function (res) { },
          });
     },
     onShow: function () {
          // 页面显示
          var vm = this;
          vm.onLoad()
          var length = vm.data.text.length * vm.data.size; //文字长度
          var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
          vm.setData({
               length: length,
               windowWidth: windowWidth,
               marquee2_margin: length < windowWidth ? windowWidth - length : vm.data.marquee2_margin //当文字长度小于屏幕长度时，需要增加补白
          });
          vm.run1(); // 水平一行字滚动完了再按照原来的方向滚动
     },
     run1: function () {
          var vm = this;
          var intervaltop = setInterval(function () {
               if (-vm.data.marqueeDistance < vm.data.length) {
                    vm.setData({
                         marqueeDistance: vm.data.marqueeDistance - vm.data.marqueePace,
                    });
               } else {
                    clearInterval(intervaltop);
                    vm.setData({
                         marqueeDistance: vm.data.windowWidth
                    });
                    vm.run1();
               }
          }, vm.data.intervaltop);
     },

     isLogin: function (_url) {
          if (app.globalData.hasLogin) {
               wx.navigateTo({
                    url: _url
               });
          } else {
               wx.navigateTo({
                    url: "/pages/auth/login/login"
               });
          }
     },

     goNearShop() {
          var url = "/pages/nearShops/nearShops"
          this.isLogin(url)
     },

     turnToNbScan: function () {
          if (!app.globalData.hasLogin) {
               wx.navigateTo({
                    url: "/pages/auth/login/login"
               });
               return false;
          }
          let this_ = this;
          console.log('开始扫码');
          wx.showLoading({
               title: '加载中',
               mask: true
          });
          wx.scanCode({
               success: (res) => {
                    var deviceNo = res.result.split('=')[1];
                    util.request(api.isBuy, {
                         deviceNo: deviceNo
                    }).then(function (res) {
                         if (res.isPay) {
                              var query = JSON.stringify(res.orderDetail);
                              var hideRefund = true;
                              if ((wx.getStorageSync('userInfo')).member == 1 && this.data.sellerId != null) {
                                   var hideRefund = false;
                              }
                              wx.navigateTo({
                                   url: '/pages/ucenter/deviceOrderDetail/deviceOrderDetail?query=' + query
                              });
                         } else {
                              wx.navigateTo({
                                   url: '/pages/home/deviceOrderList/deviceOrderList?deptId=' + res.deptId,
                              })
                         }
                         // if (app.globalData.hasLogin) {
                         //      wx.navigateTo({
                         //           url: "/pages/ucenter/devicePayment/devicePayment?query=" + JSON.stringify(res)
                         //      });
                         // } else {
                         //      wx.navigateTo({
                         //           url: "/pages/auth/login/login"
                         //      });
                         // }
                    });
               },
               fail: (error) => {
                    wx.hideLoading();
                    console.log('请提供有效的二维码');
               },
               complete: () => {
                    wx.hideLoading();
               }
          });
     }


})